import os
import shutil
import argparse

def convert_image(src: str, dst: str):
    base = 0xFF
    next = 0xD8
    gifA = 0x47
    gifB = 0x49
    pngA = 0x89
    pngB = 0x50
    with open(src, 'rb') as src_f, open(dst, 'wb') as dst_f:
        firstV, nextV = src_f.read(2)

        jT = firstV ^ base
        jB = nextV ^ next
        gT = firstV ^ gifA
        gB = nextV ^ gifB
        pT = firstV ^ pngA
        pB = nextV ^ pngB
        v = firstV ^ base
        if jT == jB:
            v = jT
        elif gT == gB:
            v = gT
        elif pT == pB:
            v = pT

        src_f.seek(0)

        while True:
            src_bytes = src_f.read(1024)
            if src_bytes:
                bytes_to_write = bytearray()
                for b in src_bytes:
                    bytes_to_write.append(b ^ v)

                dst_f.write(bytes_to_write)
            else:
                break


def convert_foler(src_folder: str, dst_folder: str):
    if not os.path.exists(dst_folder):
        os.mkdir(dst_folder, 644)
    for path, dir_list, file_list in os.walk(src_folder):
        for f in file_list:
            if f.endswith('.dat'):
                src_f = os.path.join(path, f)
                dst_f = os.path.join(dst_folder, f.replace('.dat', '.jpg'))
                convert_image(src_f, dst_f)


if __name__ == '__main__':
    parser = argparse.ArgumentParser('')
    parser.add_argument('-s', type=str)
    parser.add_argument('-d', type=str, default='img')
    args = parser.parse_args()
    convert_foler(args.s, args.d)


